import 'package:awak/common/db/db_helper.dart';
import 'package:awak/common/models/friendship.dart';
import 'package:awak/common/models/user.dart';

class FriendshipRepository {
  static final FriendshipRepository _instance = FriendshipRepository._internal();
  factory FriendshipRepository() => _instance;
  FriendshipRepository._internal();

  // 添加好友关系
  Future<int> addFriend(int userId, int friendId) async {
    final db = await DBHelper.database;
    
    // 检查是否已经是好友
    final existing = await db.query(
      'friendship',
      where: '(userId = ? AND friendId = ?) OR (userId = ? AND friendId = ?)',
      whereArgs: [userId, friendId, friendId, userId],
    );
    
    if (existing.isNotEmpty) {
      throw Exception('Already friends');
    }
    
    final friendship = Friendship(
      userId: userId,
      friendId: friendId,
      createdAt: DateTime.now(),
    );
    
    return await db.insert('friendship', friendship.toMap());
  }

  // 删除好友关系
  Future<int> removeFriend(int userId, int friendId) async {
    final db = await DBHelper.database;
    return await db.delete(
      'friendship',
      where: '(userId = ? AND friendId = ?) OR (userId = ? AND friendId = ?)',
      whereArgs: [userId, friendId, friendId, userId],
    );
  }

  // 检查是否是好友
  Future<bool> isFriend(int userId, int friendId) async {
    final db = await DBHelper.database;
    final result = await db.query(
      'friendship',
      where: '(userId = ? AND friendId = ?) OR (userId = ? AND friendId = ?)',
      whereArgs: [userId, friendId, friendId, userId],
    );
    return result.isNotEmpty;
  }

  // 获取用户的所有好友
  Future<List<User>> getFriends(int userId) async {
    final db = await DBHelper.database;
    final result = await db.rawQuery('''
      SELECT u.* FROM user u
      INNER JOIN friendship f ON 
        (f.userId = ? AND f.friendId = u.id) OR 
        (f.friendId = ? AND f.userId = u.id)
      WHERE u.id != ?
    ''', [userId, userId, userId]);
    
    return result.map((map) => User.fromMap(map)).toList();
  }

  // 获取好友数量
  Future<int> getFriendsCount(int userId) async {
    final db = await DBHelper.database;
    final result = await db.rawQuery('''
      SELECT COUNT(DISTINCT 
        CASE 
          WHEN f.userId = ? THEN f.friendId 
          WHEN f.friendId = ? THEN f.userId 
        END
      ) as count
      FROM friendship f
      WHERE f.userId = ? OR f.friendId = ?
    ''', [userId, userId, userId, userId]);
    
    return result.first['count'] as int;
  }

  // 获取所有好友关系
  Future<List<Friendship>> getAllFriendships() async {
    final db = await DBHelper.database;
    final res = await db.query('friendship');
    return res.map((map) => Friendship.fromMap(map)).toList();
  }
}
